import 'isomorphic-fetch'

// 接口辅助方法, 返回 接口 操作 action
// _state 将会覆盖默认的 state
export default (apiConfig = {})=> {
  apiConfig = Object.assign({
    method: 'POST',
    state: 'AJAX'
  }, apiConfig)

  // 请求数据
  const request = (params)=> {
    return {
      type: `REQUEST_${params._state || apiConfig.state}`,
      params
    }
  }

  // 收到数据
  const recieve = (params, data)=> {
    return Object.assign({}, {
      params,
      type: `RECIEVE_${params._state || apiConfig.state}`,
      receivedAt: new Date()
    }, data)
  }

  // 结果处理
  const handleResult = (dispatch, params, data)=> {
    // 其他接口返回
    if(typeof data.response != 'undefined') {
      data.status = data.status
      data.msg = data.status
      if(data.pagination) {
        data.data = {
          limit: data.pagination.per_page,
          page: data.pagination.current,
          total: data.count,
          list: data.response,
          metadata: data.pagination
        }
        delete data.pagination
      } else {
        data.data = data.response
      }

      delete data.status
      delete data.status
      delete data.response
    }else if(typeof data.ResponseData != 'undefined'){
        data.data = data.ResponseData
    }

    dispatch(recieve(params, {
      status: data.status,
      data: data.data,
      message: data.info
    }))

    return data
  }

  // restful api url处理
  const restfulApiHandle = (url, params)=> {
    const keys = Object.keys(params)
    keys.map((key, i)=> {
      url = url.replace(`:${key}`, params[key])
    })
    return url
  }

  // 请求参数处理
  const searchParams = (params)=> {
    const searchParams = new URLSearchParams()
    const keys = Object.keys(params)
    keys.map(key=> {
      if(typeof params[key] != 'undefined')
        searchParams.set(key, params[key])
    })

    return searchParams
  }
  //参数处理
  function getQueryString(params) {
    const esc = encodeURIComponent;
    return Object.keys(params)
      .map(k => esc(k) + '=' + esc(params[k]))
      .join('&');
  }
  //fetch get和post 请求处理
function soFetch(params) {
    const {method, headers, data} = params;
    let qs = '', body;
    ['GET', 'DELETE'].indexOf(method) > -1 ? qs = '?' + getQueryString(data) : body = searchParams(data) // POST or PUT
    const url = params.url + qs;
    return fetch(url, { method, headers, body });
}

  return (params={}, headers={}, settings={})=> {
    const url = restfulApiHandle(apiConfig.url, params)
    const commonParams = apiConfig.fullUrl ? {} : {
      // act,公共参数
    }
    params = Object.assign(commonParams, apiConfig.params, params)

    const apiHeader = apiConfig.headers
    const headerArr = apiHeader ? Object.keys(apiHeader) : []
    if(headerArr.length && headerArr.indexOf('Auth-Token') != -1) {
      const authToken = cookie.get('authToken')
      apiConfig.headers['Auth-Token'] = authToken
    }

    // 返回 promise
    return (dispatch, getState)=> {
      dispatch(request(params))
      const ajaxSettings = Object.assign({
        url,
        method: apiConfig.method,
        data: params,
        headers: Object.assign(apiConfig.headers || {}, headers)
      }, settings)
      return soFetch(ajaxSettings).then(data=> data.json()).then(data=> {
        data = handleResult(dispatch, params, data)
        return data
      }).catch(error=> {
        console.error(error)
        const data = handleResult(dispatch, params, error)
        return data
      })
    }
  }
}
